package com.whz.gateway.handler.captcha.img;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import com.whz.gateway.common.constants.GatewayConstant;
import com.whz.gateway.common.util.RedisUtils;
import com.whz.gateway.handler.AbstractGatewayHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;

import java.util.Optional;

/**
 * 验证码校验
 *
 * @author whz
 */
@Slf4j
@Component
public class ImageCodeCheckHandler extends AbstractGatewayHandler {

    @Override
    protected Pair<Boolean, String> handler(ServerRequest request) {
        return validateCode(request);
    }

    /**
     * 短信验证码验证流程
     */
    private static Pair<Boolean, String> validateCode(ServerRequest request) {
        // 验证码
        Optional<String> code = request.queryParam(GatewayConstant.IMAGE_PARAM_CODE);
        // 随机标识
        Optional<String> t = request.queryParam(GatewayConstant.IMAGE_PARAM_T);
        if (log.isDebugEnabled()) {
            log.debug("web图片验证码:key:{}-code:{}", t, code);
        }
        if (!t.isPresent() || StrUtil.isBlank(t.get())) {
            return new Pair<>(false, "时间戳不能为空");
        }
        if (!code.isPresent() || StrUtil.isBlank(code.get())) {
            return new Pair<>(false, "验证码不能为空");
        }
        // 从redis中获取之前保存的验证码跟前台传来的验证码进行匹配
        String key = GatewayConstant.IMAGE_KEY + t.get();
        Object image = RedisUtils.get(key);
        // 验证码只用一次
        RedisUtils.del(key);
        if (image == null) {
            return new Pair<>(false, "验证码已失效");
        }
        if (!code.get().toLowerCase().equals(image)) {
            return new Pair<>(false, "验验证码错误");
        }
        return new Pair<>(true, "验验通过");
    }
}